// @ts-ignore
import { Plugin, TransformResult } from 'vite'
import Utils from '../utils'
import { NodePath } from '@babel/traverse'
import { ImportDeclaration } from 'babel-types'

export default function vitePluginChangeImportdev(): Plugin {
  return {
    name: 'vite:vite-plugin-change-importdev',
    transform(code: string, id: string): Promise<TransformResult> | TransformResult {
      let map = null
      if (id.includes('node_modules')) {
        return { code, map }
      }
      if (/.js$|.jsx$|.ts$|.tsx$|.vue$/.test(id)) {
        const magicString = Utils.getMagicString(code)
        const jsAst = Utils.getJsAst(code)
        Utils.jsAstTraverse(jsAst, {
          ImportDeclaration(ipath: NodePath<ImportDeclaration>) {
            const node = ipath.node
            if (node.source.value === 'path') { // import path from 'path'---> import path from 'path-browserify'
              magicString.overwrite(node.source.start, node.source.end, '\'path-browserify\'')
            }
          }
        })
        map = Utils.getsouceMap(magicString, code)
        code = magicString.toString()
      }
      return {
        code,
        map
      }
    }

  }
}
